//
//  MineViewController.m
//  QinrenManagers
//
//  Created by easaa on 15/6/30.
//  Copyright (c) 2015年 easaa. All rights reserved.
//

#import "MineViewController.h"

#import "ChangePasswordViewController.h"
#import "AboutHealthManagerViewController.h"

#import "VersionModel.h"

#import "UIImageView+EMWebCache.h"

#import "Unit.h"
#import "SDImageCache.h"

#import "LoginViewController.h"

@interface MineViewController ()<UITableViewDataSource,UITableViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>
{
//    NSDictionary    *audioDictionary;
    
    UIImageView     *iconImageView;//头像
    UIImage         *headImg;
    
    
    NSString        *lastVersion;//最新版本
    
    UIActionSheet *myActionSheet;
    
    
    /** < 姓名 > **/
    UITextField *nickName;
    /** < 电话 > **/
    UITextField *phoneNum;
    /** < 性别 > **/
    UITextField *sexField;
    /** < 地址 > **/
    UITextField *addressField;
    
    
    BOOL canChange;
}
@property (nonatomic, strong) UITableView * mineTableView;

@property (nonatomic, strong) NSArray * cellTextArray;
@property (nonatomic, strong) NSArray * cellDetailTextArray;

//
@property (nonatomic, strong) NSMutableArray * versionArray;

@end

@implementation MineViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        _versionArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"我的";
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *setButton = [[UIButton alloc]initWithFrame:CGRectMake(10, 0, 50, 40)];
    
    [setButton setTitle:@"修改" forState:UIControlStateNormal];
    [setButton setTitle:@"保存" forState:UIControlStateSelected];
    
    [setButton.titleLabel setFont:[UIFont systemFontOfSize:13]];
    
    [setButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [setButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    [setButton addTarget:self action:@selector(setButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * rightButtonItem = [[UIBarButtonItem alloc]initWithCustomView:setButton];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    

    //创建数据源
    [self creatData];
    
//    [self getVersionData];
    
    //创建tableView
    [self creatTableView];
    
}


#pragma mark -----------------保存按钮点击事件-----------------------
- (void)setButtonClick:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    
    canChange = sender.selected;
    if (!canChange) {
        NSLog(@"上传修改信息");
        phoneNum.userInteractionEnabled = NO;
        nickName.userInteractionEnabled = NO;
        addressField.userInteractionEnabled = NO;
        sexField.userInteractionEnabled = NO;

        User *user = [User sharedUser];
        user.employee_truename = nickName.text;
        
        user.employee_phone = phoneNum.text;
        user.employee_address = addressField.text;
        
        if ([sexField.text isEqualToString:@"男"]) {
            user.employee_gender = 1;

        }else {
            user.employee_gender = 2;
        }
        
        
        [self reloadPersonalInfomation];
        
    }else {
        phoneNum.userInteractionEnabled = YES;
        nickName.userInteractionEnabled = YES;
        addressField.userInteractionEnabled = YES;
    }
}




- (void)creatData
{
    
    User *user = [User sharedUser];
    _cellDetailTextArray = [NSMutableArray array];
    
    _cellTextArray = @[@"姓名",@"性别",@"职业",@"电话",@"管理人数",@"所属地区",@"修改密码",@"关于亲仁健康管家"];
    _cellDetailTextArray = @[user.employee_truename.length>0?user.employee_truename:@"暂无信息",
                             user.employee_gender==1?@"男":@"女",
                             user.role_name,
                             user.employee_phone,
                             [NSString stringWithFormat:@"%ld",(long)user.customer_count],
                             user.employee_address.length > 0? user.employee_address : @"暂无信息"];
//   _cellDetailTextArray = @[@"王小二",@"男",@"健康管家",@"59",@"南京市"];
    
}

- (void)creatTableView
{
    _mineTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H) style:UITableViewStylePlain];
    _mineTableView.backgroundColor = [UIColor clearColor];
    _mineTableView.delegate = self;
    _mineTableView.dataSource = self;
    _mineTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    [self.view addSubview:_mineTableView];
    
    
    UIView *tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 60)];
    tableHeaderView.backgroundColor = [UIColor clearColor];
    _mineTableView.tableHeaderView = tableHeaderView;
    
    //头像view
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 10, SCREEN_W, 60)];
    headerView.backgroundColor = [UIColor whiteColor];
    [tableHeaderView addSubview:headerView];
    
    //头像Label
    UILabel *headerLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 40, 60)];
    headerLabel.text = @"头像";
    headerLabel.font = [UIFont systemFontOfSize:13];
    [headerView addSubview:headerLabel];
    
    //头像imageView
    iconImageView = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_W-15-20-15-60, 0, 60, 60)];
    iconImageView.layer.masksToBounds = YES;
    iconImageView.layer.cornerRadius = 30;
    iconImageView.userInteractionEnabled = YES;
    User *user = [User sharedUser];
    
   
   [iconImageView sd_setImageWithURL:[NSURL URLWithString:user.employee_img] placeholderImage:[UIImage imageNamed:@"touxiang.jpg"]];

    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeUserImage)];
    [iconImageView addGestureRecognizer:tap];

//    headerImageView.backgroundColor = [UIColor greenColor];
    [headerView addSubview:iconImageView];
    
//底部退出登录和检测更新
    
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 60)];
    
    footerView.backgroundColor = [UIColor clearColor];
    _mineTableView.tableFooterView = footerView;
    
    UIButton * exitButton = [[UIButton alloc]initWithFrame:CGRectMake(50, 10, SCREEN_W - 100, 40)];
    
    [exitButton setTitle:@"退出登录" forState:UIControlStateNormal];
    exitButton.titleLabel.font = [UIFont systemFontOfSize:16];//title字体大小
    exitButton.titleLabel.textAlignment = NSTextAlignmentCenter;//设置title的字体居中
    [exitButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//设置title在一般情况下为色字体
    [exitButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];//设置title在button被选中情况下为灰色字体
    exitButton.backgroundColor = [UIColor colorWithRed:114.0/255 green:198.0/255 blue:76.0/255 alpha:1];
    exitButton.layer.cornerRadius = 5;
    exitButton.clipsToBounds = YES;

    [exitButton addTarget:self action:@selector(exitButtonCliked) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * checkVersionButton = [[UIButton alloc]initWithFrame:CGRectMake(50, 10, SCREEN_W - 100, 40)];
    
    [checkVersionButton setTitle:@"检测更新" forState:UIControlStateNormal];
    checkVersionButton.titleLabel.font = [UIFont systemFontOfSize:16];//title字体大小
    checkVersionButton.titleLabel.textAlignment = NSTextAlignmentCenter;//设置title的字体居中
    [checkVersionButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//设置title在一般情况下为色字体
    [checkVersionButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];//设置title在button被选中情况下为灰色字体
    checkVersionButton.backgroundColor = Lightlightcolor;
    checkVersionButton.layer.cornerRadius = 5;
    checkVersionButton.clipsToBounds = YES;

    
    [checkVersionButton addTarget:self action:@selector(onCheckVersion) forControlEvents:UIControlEventTouchUpInside];

    
//    [footerView addSubview:checkVersionButton];
    [footerView addSubview:exitButton];
}

#pragma mark - --------------获取版本更新网络请求
- (void)getVersionData {

    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    
    NSDictionary *parameters = @{@"type":@"4"};
    NSLog(@"%@",parameters);
    [manager GetWithParameters:parameters method:@"get.app.version" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"版本检测的dictonary :%@",[dictionary description]);
        
        
        if ([[dictionary objectForKey:@"verification"]intValue] == 1)
        {
            for (NSDictionary *dataDic in dictionary[@"data"]) {
                
                VersionModel * versionModel = [[VersionModel alloc]init];
                [versionModel setValuesForKeysWithDictionary:dataDic];
                
                [_versionArray addObject:versionModel];
                
            }
            
        }
        else
        {
            NSString *error = [dictionary objectForKey:@"error"];
            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD showErrorWithStatus:error];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
    }];
    
}

#pragma mark - --------------更新个人信息网络请求----------------
- (void)reloadPersonalInfomation {
    
    User *user = [User sharedUser];
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    
    NSDictionary *parameters = @{@"employee_id":user.employee_id,
                                 @"truename":user.employee_truename,
                                 @"gender":[NSString stringWithFormat:@"%ld",(long)user.employee_gender],
                                 @"phone":user.employee_phone,
                                 @"address":user.employee_address};
    NSLog(@"%@",parameters);
    [manager GetWithParameters:parameters method:@"update.manager.info" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"版本检测的dictonary :%@",[dictionary description]);
        
        
        if ([[dictionary objectForKey:@"total"]intValue] == 1)
        {
            NSLog(@"修改成功");
            [SVProgressHUD showSuccessWithStatus:@"修改成功"];
            
        }else {
            [SVProgressHUD showErrorWithStatus:@"修改失败"];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
    }];


}

#pragma mark - --------------退出，更新点击事件
- (void)exitButtonCliked {
    
    [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:YES completion:^(NSDictionary *info, EMError *error) {
        if (!error && info) {
            
            [[User sharedUser] setUserInfo:nil];
            [[SDImageCache sharedImageCache] clearDisk];
            
            [[SDImageCache sharedImageCache] clearMemory];
            
            [[UIApplication sharedApplication] unregisterForRemoteNotifications];
            
            NSLog(@"退出成功");
        }
    } onQueue:nil];
    


    [self dismissViewControllerAnimated:YES completion:^{
//    [[NSUserDefaults standardUserDefaults]setObject:@""  forKey:@"username"];
//    [[NSUserDefaults standardUserDefaults]setObject:@""  forKey:@"password"];
    }];
    
//    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
//    
//    LoginViewController *loginVC = [storyboard instantiateInitialViewController];
//    
//    [loginVC setInputTextFieldForNull];
//    
//    UINavigationController *loginNav = [[UINavigationController alloc]initWithRootViewController:loginVC];
//    
//    NSLog(@"loginVC------%@--------",loginVC);
//    
//    self.view.window.rootViewController = loginNav;
//    

}

- (void)onCheckVersion {
   
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSLog(@"系统版本的dictonary :%@？？？？？？？？",[infoDic description]);
    
    NSString *currentVersion = [infoDic objectForKey:@"CFBundleVersion"];
    NSLog(@"appVersion:%@==================",currentVersion);
    
    
    VersionModel *versionModel = _versionArray[0];
    
    lastVersion = versionModel.version_code;

    if (![lastVersion isEqualToString:currentVersion]) {
        //trackViewURL = [releaseInfo objectForKey:@"trackVireUrl"];
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:[NSString  stringWithFormat:@"当前版本为v_%@\n有新的版本更新，是否前往更新？",currentVersion] delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新", nil];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:[NSString  stringWithFormat:@"当前版本为v_%@\n有新的版本更新，请前往AppStore更新",currentVersion] delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil, nil];
        alert.tag = 10000;
        [alert show];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:[NSString  stringWithFormat:@"当前版本为v_%@\n此版本为最新版本",currentVersion]delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 10001;
        [alert show];
    }

}

//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    if (alertView.tag==10000) {
//        if (buttonIndex==1) {
//            VersionModel *versionModel = _versionArray[0];
//            NSString * updataURL = versionModel.app_url;
//            NSURL *url = [NSURL URLWithString:updataURL];
//            [[UIApplication sharedApplication]openURL:url];
//        }
//    }
//}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.cellTextArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MineCell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier];
    }
    

    
    if(indexPath.row < 6) {
        
        UILabel *cellTitle = [[UILabel alloc]initWithFrame:CGRectMake(15, 5, 80, 40)];
        
        cellTitle.font = [UIFont systemFontOfSize:13];
        cellTitle.text = _cellTextArray[indexPath.row];
        cellTitle.textAlignment = NSTextAlignmentLeft;
        cellTitle.textColor = [UIColor blackColor];
        [cell.contentView addSubview:cellTitle];
        
        switch (indexPath.row) {
            case 0:
            {
                nickName = [[UITextField alloc]initWithFrame:CGRectMake(95, 5, SCREEN_W-95, 40)];
                
                nickName.text = _cellDetailTextArray[indexPath.row];
                
                nickName.userInteractionEnabled = NO;
                nickName.font = [UIFont systemFontOfSize:14];
                
                nickName.textColor = [UIColor grayColor];
                nickName.textAlignment = NSTextAlignmentLeft;
                [cell.contentView addSubview:nickName];
                
            }
                break;
            case 1:
            {
                sexField = [[UITextField alloc]initWithFrame:CGRectMake(95, 5, SCREEN_W-95, 40)];
                
                sexField.text = _cellDetailTextArray[indexPath.row];
                sexField.userInteractionEnabled = NO;
                sexField.font = [UIFont systemFontOfSize:14];

                
                sexField.textColor = [UIColor grayColor];
                sexField.textAlignment = NSTextAlignmentLeft;
                [cell.contentView addSubview:sexField];
                
            }
                break;
            case 2:
            {
                UITextField * jobField = [[UITextField alloc]initWithFrame:CGRectMake(95, 5, SCREEN_W-95, 40)];
                
                jobField.text = _cellDetailTextArray[indexPath.row];
                jobField.userInteractionEnabled = NO;
                jobField.font = [UIFont systemFontOfSize:14];

                jobField.textColor = [UIColor grayColor];
                jobField.textAlignment = NSTextAlignmentLeft;
                [cell.contentView addSubview:jobField];
                
            }
                break;
            case 3:
            {
                phoneNum = [[UITextField alloc]initWithFrame:CGRectMake(95, 5, SCREEN_W-95, 40)];
                
                phoneNum.text = _cellDetailTextArray[indexPath.row];
                phoneNum.userInteractionEnabled = NO;

                phoneNum.font = [UIFont systemFontOfSize:14];
                phoneNum.keyboardType = UIKeyboardTypeNumberPad;

                phoneNum.textColor = [UIColor grayColor];
                phoneNum.textAlignment = NSTextAlignmentLeft;
                [cell.contentView addSubview:phoneNum];

                
            }
                break;
            case 4:
            {
                UITextField * countField = [[UITextField alloc]initWithFrame:CGRectMake(95, 5, SCREEN_W-95, 40)];
                
                countField.text = _cellDetailTextArray[indexPath.row];
                countField.userInteractionEnabled = NO;

                countField.font = [UIFont systemFontOfSize:14];
                countField.textColor = [UIColor grayColor];
                countField.textAlignment = NSTextAlignmentLeft;
                [cell.contentView addSubview:countField];
                
            }
                break;
            case 5:
            {
                addressField = [[UITextField alloc]initWithFrame:CGRectMake(95, 5, SCREEN_W-95, 40)];
                
                addressField.text = _cellDetailTextArray[indexPath.row];
                addressField.userInteractionEnabled = NO;
                
                addressField.font = [UIFont systemFontOfSize:14];
                addressField.textColor = [UIColor grayColor];
                addressField.textAlignment = NSTextAlignmentLeft;
                [cell.contentView addSubview:addressField];
                
            }
                break;
                
            default:
                break;
        }
        
    }
    
    
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if(indexPath.row > 5) {
        UILabel *textLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, SCREEN_W-15, 50)];
        textLabel.text = _cellTextArray[indexPath.row];
        textLabel.font = [UIFont systemFontOfSize:13];
        [cell.contentView addSubview:textLabel];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
    }
    
    return cell;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (canChange) {
        if(indexPath.row == 1) {
            myActionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"男", nil),NSLocalizedString(@"女",nil), nil];
            myActionSheet.tag = 1002;
            [myActionSheet showInView:self.view];
        }
    }
    
    if(indexPath.row == 6) {
        ChangePasswordViewController * changePasswordViewController = [[ChangePasswordViewController alloc]init];
        [self.navigationController pushViewController:changePasswordViewController animated:NO];
    }

    if(indexPath.row == 7) {
        AboutHealthManagerViewController * aboutHealthManagerViewController = [[AboutHealthManagerViewController alloc]init];
        [self.navigationController pushViewController:aboutHealthManagerViewController animated:NO];
    }
}

#pragma mark -- 换头像
- (void)changeUserImage
{
    UIActionSheet *action1 = [[UIActionSheet alloc] initWithTitle:@"选择图片"
                                                        delegate:self
                                               cancelButtonTitle:@"取消"
                                          destructiveButtonTitle:nil
                                               otherButtonTitles:@"拍照",@"从相册中选取", nil];
    action1.tag = 1001;
    [action1 showInView:self.view];
    
    
}

#pragma mark -- UIActionSheet 代理 调用相机和相册
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 1002) {
        if (buttonIndex==0) {
            
            sexField.text=@"男";
        }
        else
        {
            sexField.text=@"女";
        }
    }
    else if (actionSheet.tag == 1001){
        NSInteger sourceType;
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            switch (buttonIndex)
            {
                case 0:
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 1:
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                default:
                    return;
                    break;
            }
        }
        else
        {
            switch (buttonIndex)
            {
                case 0:
                    return;
                    break;
                case 1:
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                default:
                    return;
                    break;
            }
            
        }
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
        [self presentViewController:imagePickerController animated:YES completion:^{
            //        NSLog(@"gg");
        }];

    
    }
}

//时间
-(NSString*)creatTimeData
{
    NSDateFormatter *dateFormateter = [[NSDateFormatter alloc] init];
    [dateFormateter setDateFormat:@"yyyy-MM-dd-HH-mm-ss"];
    NSString *dataString = [dateFormateter stringFromDate:[NSDate date]];
    return dataString;
}

#pragma mark - UIImagePicker delegate

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    UIImage *fileImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSString *dateString = [self creatTimeData];
    //生成文件名：
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString  *diskCachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"QinRenCaches/image"];
    
    //没有文件夹 创建个文件夹
    if (![[NSFileManager defaultManager] fileExistsAtPath:diskCachePath])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:diskCachePath
                                  withIntermediateDirectories:YES
                                                   attributes:nil
                                                        error:NULL];
    }
    
    float scale = 0.0;
    if (fileImage.size.width > 320)
    {
        scale = 320 / fileImage.size.width;
    }
    else
    {
        scale = 1.0;
    }
    //压缩图片
    UIImage *sendImage = [self scaleImage:[Unit rotateImage:fileImage] toScale:scale];
    
    //把图片转成data 存进沙盒中
    NSString *pathString = [diskCachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",dateString]];
    NSData *imageData = UIImagePNGRepresentation(sendImage);
    [imageData writeToFile:pathString atomically:YES];
    
    
    //退出相册
    [self dismissViewControllerAnimated:YES completion:^{
        [NSThread detachNewThreadSelector:@selector(uploadImage:) toTarget:self withObject:sendImage];
        //上传图片
        [SVProgressHUD showSuccessWithStatus:@"正在上传图片"];
    }];
    
    
}

#pragma mark 头像加密 上传

- (void)uploadImage:(UIImage *)image {
    NSData *data = UIImageJPEGRepresentation([self scaleImage:image toScale:0.00000001] , 0.1);
    data = UIImagePNGRepresentation(image);
    
    User *user = [User sharedUser];
    
    NSDictionary *parameters2 = [NSDictionary dictionaryWithObjectsAndKeys:
                                 user.employee_id,@"user_id",@"1",@"type",
                                 nil];
    
    [self postPicture:data withDic:parameters2 withBlock:^(id obj, NSError *error) {
        
         NSLog(@"dictonary :%@ error = %@",[obj description],[obj objectForKey:@"error"]);
        
                 if ([[obj objectForKey:@"total"]intValue] == 1)
                 {
                     [SVProgressHUD showSuccessWithStatus:@"上传图片成功"];
                     iconImageView.image = image;
                     [[SDImageCache sharedImageCache] clearDisk];
                     
                        [[SDImageCache sharedImageCache] clearMemory];//可有可无
                     user.employee_img = [obj[@"error"] substringFromIndex:5];
//                     [iconImageView sd_setImageWithURL:[NSURL URLWithString:user.employee_img] placeholderImage:[UIImage imageNamed:@""]];
                     NSLog(@"%@",[obj[@"error"] substringFromIndex:5]);
        
                 }else
                 {
                     [SVProgressHUD showSuccessWithStatus:@"上传图片失败"];
                     DLog(@"上传失败");
                     NSLog(@"error = %@",error);
            
                 }

    }];


}

/**
 *  @author HHL, 15-08-05 19:08:29
 *
 *  post带参数的图片
 *
 *  @param image2    图片
 *  @param sugestDic 需要上传的参数
 *  @param block     回掉返回的数据
 */
- (void)postPicture:(NSData*)image2
            withDic:(NSDictionary*)sugestDic
          withBlock:(void (^)(id obj, NSError *error))block
{
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";/** < <#Description#> > **/
    /** < 上传的URL > **/
    //NSString *urlString =  @"http://192.168.0.107:810/upload.aspx";
    NSString *urlString = [NSString stringWithFormat:@"%@/upload.aspx",baseUrla];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
    
    NSArray *keys= [sugestDic allKeys];
    //遍历keys
    for(int i=0;i<[keys count];i++)
    {
        NSString *key=[keys objectAtIndex:i];
        //如果key不是图片，说明value是字符类型，比如name：Boris
        if(![key isEqualToString:@"employee_img"])
        {
            //添加分界线，换行
            [body appendFormat:@"%@\r\n",MPboundary];
            //添加字段名称，换2行
            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
            //添加字段的值
            [body appendFormat:@"%@\r\n",[sugestDic objectForKey:key]];
        }
    }
    
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明图片字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"files\"; filename=\"boris.png\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:image2];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    
    [request setHTTPBody:myRequestData];
    
    [request setHTTPMethod:@"POST"];
    //建立连接，设置代理
    /**
     *  @author easaa, 15-08-05 19:08:14
     *
     *  同步
     */
#if 0
    NSError *error = nil;
    NSHTTPURLResponse *response = nil;
    NSData *urlData = [NSURLConnection
                       sendSynchronousRequest:request
                       returningResponse: &response
                       error: &error];
    id resultDic = [NSJSONSerialization JSONObjectWithData:urlData
                                                   options:NSJSONReadingMutableLeaves
                                                     error:nil];
#else
    
    /**
     *  @author easaa, 15-08-05 19:08:30
     *
     *  异步上传图片
     *
     *  @return data 和 error
     */
    [NSURLConnection
     sendAsynchronousRequest:request
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response, NSData *data,
                         NSError *connectionError) {
         
         if (!connectionError)
         {
             
             //系统自带JSON解析
             id resultDic = [NSJSONSerialization JSONObjectWithData:data
                                                            options:NSJSONReadingMutableLeaves
                                                              error:nil];
             if (block)
             {
                 block(resultDic, nil);
             }
         }
         else
         {
             if (block)
             {
                 block(nil, connectionError);
             }
         }
     }];
    
    
#endif
}


-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark -- 提示框
-(void)showAlert:(NSString*)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                    message:message
                                                   delegate:nil
                                          cancelButtonTitle:@"知道了"
                                          otherButtonTitles:nil, nil];
    [alert show];
}

#pragma mark 等比压缩图片
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return scaledImage;
    
}


@end
